package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

type ChapterBufio struct {
}

func main() {
	chapterBufio := ChapterBufio{}
	//chapterBufio.bufferReader()
	//chapterBufio.bufferWriter()
	chapterBufio.bufferScanner()

}

func (c *ChapterBufio) bufferScanner() {
	str := "Never put off what you can do today until tomorrow."
	reader := bufio.NewReader(strings.NewReader(str))
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	for scanner.Scan() {
		fmt.Println("读取到的单词: ", scanner.Text())
		if scanner.Text() == "q!" {
			fmt.Println("数据读取完毕")
			break
		}
	}
}

func (c *ChapterBufio) bufferWriter() {
	testFilePath := "/Users/liuwx/Documents/project/go-demo/abc/efg/test.txt"
	testFile, err := os.Open(testFilePath)
	if err != nil {
		fmt.Printf("打开 testFilePath %s  文件失败,错误原因 %s \n ", testFilePath, err.Error())
		return
	}
	defer func(testFile *os.File) {
		err := testFile.Close()
		if err != nil {
			fmt.Println("关闭文件 testFile")
		}
	}(testFile)

	outputPath := "/Users/liuwx/Documents/project/go-demo/mkdir/abc/test.txt"
	outputFile, err := os.Open(outputPath)
	if err != nil {
		fmt.Printf("打开 outputPath %s  文件失败,错误原因 %s \n ", outputPath, err.Error())
		return
	}
	defer func(outputFile *os.File) {
		err := outputFile.Close()
		if err != nil {
			fmt.Println("关闭文件 outputFile")
		}
	}(outputFile)
	reader := bufio.NewReader(testFile)
	writer := bufio.NewWriter(outputFile)
	for {
		bytes, err := reader.ReadBytes(' ')
		if err == io.EOF {
			fmt.Println("写入文件结束")
			break
		}
		if err != nil {
			fmt.Printf("读取字节数据 失败,错误原因 %s \n ", err.Error())
			return
		}
		num, err := writer.Write(bytes)
		if err != nil {
			fmt.Printf("写入字节数据 失败,错误原因 %s \n ", err.Error())
			return
		}
		err = writer.Flush()
		if err != nil {
			fmt.Printf("flush 字节数据 失败,错误原因 %s \n ", err.Error())
			return
		}
		fmt.Printf("写入 %d 字节数据 \n ", num)
	}
}

func (c *ChapterBufio) bufferReader() {
	testFilePath := "/Users/liuwx/Documents/project/go-demo/chapter-print.go"
	testFile, err := os.Open(testFilePath)
	if err != nil {
		fmt.Printf("打开 testFilePath %s  文件失败,错误原因 %s \n ", testFilePath, err.Error())
		return
	}
	defer func(testFile *os.File) {
		err := testFile.Close()
		if err != nil {
			fmt.Println("关闭文件 testFile")
		}
	}(testFile)

	reader := bufio.NewReader(testFile)
	fmt.Printf("reader %T \n ", reader)
	for {

		readString, err := reader.ReadString('\n')
		if err == io.EOF {
			fmt.Println("文件内容读取完毕")
			break
		}
		if err != nil {
			fmt.Printf("读取文件行数据 %s  失败,错误原因 %s \n ", testFilePath, err.Error())
			return
		}

		fmt.Println("内容是: ", readString)

	}
}
